<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\Log;

/**
 *  用户 技工管理
 */
class Artificer extends Api
{
    protected $noNeedRight = '*';

    protected $beforeActionList = [
        'check'
    ];

    protected $artificer_id;

    protected $model;

    /**
     * 检测是否是技工，平台是否通过审核
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function check()
    {
        $identity = $this->auth->identity;
        if($identity !== '30'){
            $this->error('技工尚未入驻');
        }
        $this->model = new \app\common\model\Artificer();
        $row = $this->model->where(['user_id'=>['=',$this->auth->id]])->order('id desc')->find();
        if($row->state !== '20'){
            $this->error('平台尚未审核通过');
        }
        $this->artificer_id  = $row->id;
    }

    /**
     * 开启关闭接单开关
     * @return void
     */
    public function changeTake()
    {
        Db::startTrans();
        try {
            $status = $this->request->post('status/d',0);    //  1：开启  0：关闭
            $row = $this->model->get($this->artificer_id);
            if(empty($row)){
                $this->error(__('No results were found'));
            }
            $row->allowField(true)->save(['take_switch'=>$status]);
            $user = $this->auth->getUser();
            $user->take_switch = $status;
            $user->save();
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error(__('Operation failed'));
        }
        $this->success(__('Operation completed'));
    }

    /**
     * 技工信息
     * @return void
     */
    public function index()
    {
        try {
            $row = $this->model->where(['user_id'=>['=',$this->auth->id],'state'=>['=','20']])->field(['user_id','amount','pay_status','pay_way','reason','verifytime','transaction_id','refund_status','refundtime','createtime','updatetime','deletetime'],true)->find();
            $this->success('success',$row);
        }catch (Exception $e){
            $this->error(__('Network error'));
        }
    }

    /**
     * 编辑技工信息
     * @return void
     */
    public function save()
    {
        try {
            $row = $this->model->get($this->artificer_id);
            if(empty($row)){
                $this->error(__('No results were found'));
            }
            $param = $this->request->post();
            $row->allowField(true)->save($param);
            $this->success(__('Operation completed'));
        }catch (Exception $e){
            Log::write('错误：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 订单列表
     * @return void
     */
    public function orderList()
    {
        try {
            $limit = $this->request->post('limit/d',10);
            $page = $this->request->post('page/d',1);
            $state = $this->request->post('state');   //0:全部   1：待处理   2：待确认   3：已完成   4：已取消
            $where = [
                'distribution_status' => ['=','20'],
                'artificer_id' => ['=',$this->artificer_id]
            ];
            switch ($state){
                case '1':
                    $where['take_status'] = '10';   // 待接单
                    $where['order_status'] = '10';  // 订单进行中
                    break;
                case '2':
                    $where['take_status'] = '20';    // 已接单
                    $where['aid_status'] = '10';     // 待确认是否到达现场、待援助完成拍照
                    $where['order_status'] = '10';   // 订单进行中
                    break;
                case '3':
                    $where['take_status'] = '20';    // 已接单
                    $where['reach_status'] = '20';    // 到达现场
                    $where['aid_status'] = '20';      // 援助完成
                    $where['order_status'] = '10';    // 订单进行中
                    break;
                case '4':
                    $where['order_status'] = '30';    // 已取消
                    break;
            }
            $model = new \app\common\model\order\Rescue();
            $list = $model->list($where,$limit,$page);
            if($list === false){
                $this->error($model->getError());
            }
            $this->success(__('success'),$list);
        }catch (Exception $e){
            Log::write('错误：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 订单详情
     * @return void
     */
    public function orderInfo()
    {
        try {
            $id = $this->request->post('id/d');
            $model = new \app\common\model\order\Rescue();
            $data = $model->details($id);
            if($data === false){
                $this->error($model->getError());
            }
            if($data->artificer_id !== $this->artificer_id){
                $this->error('参数错误');
            }
            $this->success(__('success'),$data);
        }catch (Exception $e){
            Log::write('错误：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
    }

    /**
     * 立即前往
     * @return void
     */
    public function depart()
    {
        Db::startTrans();
        try {
            $id = $this->request->post('id/d');
            $model = new \app\common\model\order\Rescue();
            $data = $model->details($id);
            if($data === false){
                $this->error($model->getError());
            }
            if(($data->artificer_id !== $this->artificer_id) || ($data->take_status !== '10') || ($data->order_status != '10')){
                $this->error('参数错误');
            }
            $data->take_status = '20';
            $data->taketime = time();
            $data->allowField(true)->save();
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            Log::write('错误：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
        $this->success(__('Operation completed'));
    }

    /**
     * 确认到达
     * @return void
     */
    public function confirmArrival(){
        Db::startTrans();
        try {
            $id = $this->request->post('id/d');
            $model = new \app\common\model\order\Rescue();
            $data = $model->details($id);
            if($data === false){
                $this->error($model->getError());
            }
            if(($data->artificer_id !== $this->artificer_id) || ($data->take_status !== '20') || ($data->reach_status !== '10') || ($data->order_status != '10')){
                $this->error('参数错误');
            }
            $data->reach_status = '20';
            $data->reachtime = time();
            $data->allowField(true)->save();
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            Log::write('错误：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
        $this->success(__('Operation completed'));
    }

    /**
     * 技工援助完成
     * @return void
     */
    public function aidFinish()
    {
        Db::startTrans();
        try {
            $id = $this->request->post('id/d');
            $proof_images = $this->request->post('proof_images');
            $model = new \app\common\model\order\Rescue();
            $data = $model->details($id);
            if($data === false){
                $this->error($model->getError());
            }
            //take_status   技工接单:10=否,20=是  reach_status技工到达现场:10=未到达,20=已到达   aid_status 技工援助完成:10=未完成,20=已完成
            if(($data->artificer_id !== $this->artificer_id) || ($data->take_status !== '20') || ($data->reach_status !== '20') || ($data->aid_status !== '10') || ($data->order_status != '10')){
                $this->error('参数错误');
            }
            $data->aid_status = '20';
            $data->aidtime = time();
            $data->proof_images = $proof_images;
            $data->allowField(true)->save();
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            Log::write('错误：'.$e->getMessage(),'error',true);
            $this->error(__('Network error'));
        }
        $this->success(__('Operation completed'));
    }
}